package service;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

/**
 * @author: bohao
 */
public class ProgrammaticFooService {
    private final TransactionTemplate transactionTemplate1;
    private final TransactionTemplate transactionTemplate2;

    private JdbcTemplate jdbcTemplate1;
    private JdbcTemplate jdbcTemplate2;

    public ProgrammaticFooService(PlatformTransactionManager transactionManager, DataSource dataSource) {
        transactionTemplate1 = new TransactionTemplate(transactionManager);
        transactionTemplate2 = new TransactionTemplate(transactionManager);
        transactionTemplate1.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

        //transactionTemplate2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        jdbcTemplate1 = new JdbcTemplate(dataSource);
        jdbcTemplate2 = new JdbcTemplate(dataSource);
    }

    public void update() {
        transactionTemplate1.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                jdbcTemplate2.update("update USER_INFO set age = age + 20 where UNAME = 'tangmaru'");

                throw new RuntimeException("in failed");
                //System.out.println("in success!");
            }
        });
    }

    public void require() {
        transactionTemplate2.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {



                try {
                    update();
                } catch (Exception e) {
                    System.out.println("update failed: " + e.getMessage());
                }

                jdbcTemplate1.update("update USER_INFO set age = age + 10");
                //insertFoo(new Message());
                System.out.println("out success!");
            }

        });
    }

}
